#
# Copyright 2009 Red Hat, Inc. and/or its affiliates.
#
# Licensed to you under the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  See the files README and
# LICENSE_GPL_v2 which accompany this distribution.
#

from time import strftime
from qaDBconnect import db

class DBcommunicator(object):

    def __init__(self, logFile, dbOut = False):
        '''
        initialize parameters for qtms DB logging
        '''
        self.db = db
	self.dbOut = dbOut
        self.logFile = logFile


    def initDBParams(self, storageType, buildName, buildVer, buildRev, setup):
        self.dbOut = True
        self.buildName = buildName
        self.storageType = storageType
        self.buildVer = buildVer
        self.buildRev = buildRev
        self.iterations = 1
        self.db_headers = "storageType:str,testStep:str,status:str"
        self.db_header_types = "str,str,str"
        self.iteration_start_time = "00:00:00"
        self.db.setParams(setup)


    def testStart(self, testName):
        '''
        Create new entry for test
        '''
        if self.dbOut == True:
            resetTestId = True
            self.db.testStartTime("vdsm_" + testName + "_v1", self.iterations,
                self.db_headers, self.db_header_types, self.buildName,
                self.buildRev, self.buildVer, '', '', resetTestId)
            self._setIterationStartTime()

    def _getTime(self):
        return strftime('%X')


    def _setIterationStartTime(self):
        '''
        Initialize test iteration start time
        '''
        self.iteration_start_time = self._getTime()


    def testPrintInfo(self, iterationStatus, logText):
        '''
        Save test iteration in DB
        '''
        if self.dbOut == True:
            iteration_end_time = self._getTime()
            infoLine = self.storageType + ' , ' + logText + ' , ' + str(iterationStatus)
            self.iterations += 1
            self.db.iterationInfo(iteration=self.iterations, start=self.iteration_start_time,
                end=iteration_end_time, status=iterationStatus, info=infoLine)
            self._setIterationStartTime()


    def testEnd(self, testStatus):
        '''
        Save test status in DB
        '''
        if self.dbOut == True:
            #qtms log
            self.db.testStatus(testStatus, log_location = str(self.logFile))

